package br.usp.ime.servicosusp.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import android.util.Log;

public class MySqlDatabase {
	Connection conn; 
	
	public MySqlDatabase() {
		conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			
			String url="192.168.0.101/";
			String databaseName="TesteAncoras";
			String username="lopespt";
			String pass="cessna";
				
			
		    //conn =DriverManager.getConnection(("jdbc:mysql://%1%2").replace("%1", url).replace("%2", databaseName),username,pass);
			conn =DriverManager.getConnection("jdbc:mysql://%1/%2".replace("%1", url).replace("%2", databaseName),username,pass);
		    // Do something with the Connection
		    if(conn==null){
		    	throw new NullPointerException("CONN é null!");
		    }
		    
		} catch (SQLException ex) {
		    // handle any errors
		   // System.out.println("SQLException: " + ex.getMessage());
		   // System.out.println("SQLState: " + ex.getSQLState());
		   // System.out.println("VendorError: " + ex.getErrorCode());
			Log.e("ServicosUSP - ERRO", ex.getMessage());
			Log.e("ServicosUSP - ERRO", ex.getSQLState());
			Log.e("ServicosUSP - ERRO", String.valueOf(ex.getErrorCode()));
		} catch (InstantiationException e) {
			Log.e("ERRO!!", e.getMessage());
		} catch (IllegalAccessException e) {
			Log.e("ERRO!!", e.getMessage());
		} catch (ClassNotFoundException e) {
			Log.e("ERRO!!", e.getMessage());
		}
		
	}
	
	ResultSet executeSql(String sql){
		try {
			 Statement state = conn.createStatement();
			 ResultSet r = state.executeQuery(sql);
			return r;
		} catch (SQLException e) {
			Log.e("ERRO!", e.getMessage());
			return null;
		}
	}
	
	String teste(){
		 try {
			 Statement state = conn.createStatement();
			 ResultSet r = state.executeQuery("Select * from wp_users");
			r.next();
			return r.getString("user_login");
		} catch (SQLException e) {
			Log.e("ERRO!", e.getMessage());
			return "Ferrou";
		}
		 
		
	}
	
	
}
